package com.zhangkunhao.notes.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

/**
 * 发邮箱的工具类
 *
 * @author 20642
 */
public class SendEmailUtil {
    /**
     * 发件人
     */
    static final String USER = "2064272436@qq.com";
    /**
     * 授权码
     */
    static final String PASSWD = "botvuqldtzdkebcj";
    /**
     * 验证码位数
     */
    static final Integer PLACE = 4;

    static final String TO_MAIL = "2064272436@qq.com";
    static String subject = "忘记密码的验证码：";

    static Properties properties = new Properties();
    static Authenticator authenticator = null;

    public static void initProp() throws Exception {
        properties.setProperty("mail.host", "smtp.qq.com");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.timeout", "1000");
        properties.setProperty("mail.smtp.port", "25");


        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);

        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);


        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USER, PASSWD);
            }
        };
    }

    public static Session getSession() {
        return Session.getDefaultInstance(properties, authenticator);
    }

    public static String sendEmailCheckCode() throws Exception {
        String codeText = "";

        Random r = new Random();
        for (int i = 0; i < PLACE; i++) {
            codeText += r.nextInt(10);
        }
        System.out.println("邮箱验证码codeText=" + codeText);

        SendEmailUtil.initProp();

        Session session = getSession();

        //session.setDebug(true)

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(USER));
        msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(TO_MAIL));
        msg.setSubject(subject);
        msg.setContent(codeText, "text/html;charset=utf-8");
        msg.saveChanges();
        Transport.send(msg);
        return codeText;
    }

}
